package user.fragment;

import android.annotation.SuppressLint;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import com.example.xfengshopping.R;
import user.fragment.OrderAdapter;
import user.fragment.GoodsItem;
import utils.TokenUtils;

public class OrderDetailActivity extends AppCompatActivity {

    private TextView tvOrderStatus;
    private TextView tvOrderNo;
    private TextView tvOrderTime;
    private TextView tvGoodsAmount;
    private TextView tvShippingMethod;
    private Button btnCancelOrder;
    private RecyclerView rvGoodsList;

    private String orderNo; // 当前订单号
    private SharedPreferences sharedPreferences;

    @SuppressLint("MissingInflatedId")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_order_detail);

        // 初始化视图组件
        tvOrderStatus = findViewById(R.id.tv_order_status);
        tvOrderNo = findViewById(R.id.tv_order_no);
        tvOrderTime = findViewById(R.id.tv_order_time);
        tvGoodsAmount = findViewById(R.id.tv_goods_amount);
        tvShippingMethod = findViewById(R.id.tv_shipping_method);
        btnCancelOrder = findViewById(R.id.btn_cancel_order);
        rvGoodsList = findViewById(R.id.rv_goods_list); // 新增 RecyclerView


        // 获取传递过来的订单号
        orderNo = getIntent().getStringExtra("orderNo");

        // 检查登录状态
        if (!TokenUtils.isLoggedIn(this)) {
            Toast.makeText(this, "请先登录", Toast.LENGTH_SHORT).show();
            finish();
            return;
        }


        // 加载订单详情
        loadOrderDetail(orderNo);

        // 设置取消订单按钮点击事件
        btnCancelOrder.setOnClickListener(v -> cancelOrder(orderNo));
    }

    /**
     * 加载订单详情
     */
    private void loadOrderDetail(String orderNo) {
        new Thread(() -> {
            String token = TokenUtils.getToken(this);


            try {
                URL url = new URL("http://47.99.134.126:28019/api/v1/order/" + orderNo);
                HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                conn.setRequestMethod("GET");
                conn.setRequestProperty("token", token);

                int responseCode = conn.getResponseCode();
                if (responseCode == HttpURLConnection.HTTP_OK) {
                    InputStream is = conn.getInputStream();
                    ByteArrayOutputStream baos = new ByteArrayOutputStream();
                    byte[] buffer = new byte[1024];
                    int len;
                    while ((len = is.read(buffer)) > 0) {
                        baos.write(buffer, 0, len);
                    }
                    String response = baos.toString();

                    JSONObject obj = new JSONObject(response);
                    int resultCode = obj.getInt("resultCode");

                    if (resultCode == 200) {
                        JSONObject data = obj.optJSONObject("data");
                        if (data != null) {
                            String orderStatus = data.optString("orderStatusString", "未知状态");
                            String orderNoStr = data.optString("orderNo", "未知编号");
                            String createTime = data.optString("createTime", "未知时间");
                            double totalPrice = data.optDouble("totalPrice", 0.0);
                            String shippingMethod = "普通快递"; // 默认值

                            JSONArray items = data.optJSONArray("newBeeMallOrderItemVOS");
                            if (items != null) {
                                runOnUiThread(() -> updateUI(orderStatus, orderNoStr, createTime, totalPrice, shippingMethod, items));
                            } else {
                                runOnUiThread(() -> Toast.makeText(this, "订单商品项为空", Toast.LENGTH_SHORT).show());
                            }
                        } else {
                            runOnUiThread(() -> Toast.makeText(this, "数据格式错误", Toast.LENGTH_SHORT).show());
                        }
                    } else {
                        runOnUiThread(() -> Toast.makeText(this, "加载订单详情失败: " + obj.optString("message", "未知错误"), Toast.LENGTH_SHORT).show());
                    }
                } else {
                    runOnUiThread(() -> Toast.makeText(this, "加载订单详情失败: HTTP Response Code " + responseCode, Toast.LENGTH_SHORT).show());
                }
            } catch (Exception e) {
                Log.e("OrderDetailActivity", "加载订单详情失败：" + e.getMessage());
                runOnUiThread(() -> Toast.makeText(this, "加载订单详情失败", Toast.LENGTH_SHORT).show());
            }
        }).start();
    }

    /**
     * 更新 UI 显示订单信息
     */
    private void updateUI(String orderStatus, String orderNoStr, String createTime, double totalPrice, String shippingMethod, JSONArray items) {
        tvOrderStatus.setText("订单状态: " + orderStatus);
        tvOrderNo.setText("订单编号: " + orderNoStr);
        tvOrderTime.setText("下单时间: " + createTime);
        tvGoodsAmount.setText("商品金额: ¥" + totalPrice);
        tvShippingMethod.setText("配送方式: " + shippingMethod);

        List<GoodsItem> goodsList = new ArrayList<>();

        try {
            for (int i = 0; i < items.length(); i++) {
                JSONObject item = items.getJSONObject(i);
                String goodsName = item.optString("goodsName", "未知商品");
                double sellingPrice = item.optDouble("sellingPrice", 0.0);
                String goodsCoverImg = item.optString("goodsCoverImg", ""); // 获取图片 URL
                int goodsQuantity = item.optInt("goodsCount", 1); // 获取商品数量，默认为 1

                if (!goodsCoverImg.isEmpty()) {
                    goodsList.add(new GoodsItem(
                            goodsCoverImg, // 图片 URL
                            goodsName,
                            "",
                            sellingPrice,
                            goodsQuantity // 传递商品数量
                    ));
                }
            }

            // 设置 RecyclerView 和适配器
            OrderGoodsAdapterNew adapter = new OrderGoodsAdapterNew(goodsList);
            rvGoodsList.setLayoutManager(new LinearLayoutManager(this));
            rvGoodsList.setAdapter(adapter);

        } catch (JSONException e) {
            Log.e("OrderDetailActivity", "解析商品项失败：" + e.getMessage());
            Toast.makeText(this, "加载商品失败", Toast.LENGTH_SHORT).show();
        }

        // 控制按钮显示
        if ("已支付".equals(orderStatus)) {
            btnCancelOrder.setVisibility(View.VISIBLE);
        } else {
            btnCancelOrder.setVisibility(View.GONE);
        }
    }



    /**
     * 发起取消订单请求
     */
    private void cancelOrder(String orderNo) {
        new AsyncTask<Void, Void, Integer>() {
            private String errorMessage = "";

            @Override
            protected Integer doInBackground(Void... voids) {
                try {
                    String token = TokenUtils.getToken(OrderDetailActivity.this);
                    if (token.isEmpty()) {
                        return HttpURLConnection.HTTP_UNAUTHORIZED;
                    }

                    URL url = new URL("http://47.99.134.126:28019/api/v1/order/" + orderNo + "/cancel");
                    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                    conn.setRequestMethod("PUT");
                    conn.setRequestProperty("token", token);
                    conn.setDoOutput(true); // 允许输出流
                    conn.connect();

                    OutputStream os = conn.getOutputStream();
                    os.write(new byte[0]); // PUT 请求体为空
                    os.flush();
                    os.close();

                    int responseCode = conn.getResponseCode();

                    if (responseCode == HttpURLConnection.HTTP_OK) {
                        InputStream is = conn.getInputStream();
                        ByteArrayOutputStream baos = new ByteArrayOutputStream();
                        byte[] buffer = new byte[1024];
                        int len;
                        while ((len = is.read(buffer)) > 0) {
                            baos.write(buffer, 0, len);
                        }
                        String response = baos.toString();
                        JSONObject obj = new JSONObject(response);

                        if (obj.getInt("resultCode") == 200) {
                            return HttpURLConnection.HTTP_OK; // 成功
                        } else {
                            errorMessage = obj.optString("message", "未知错误");
                            return HttpURLConnection.HTTP_BAD_REQUEST;
                        }
                    }
                    return responseCode;
                } catch (Exception e) {
                    errorMessage = e.getMessage();
                    return HttpURLConnection.HTTP_INTERNAL_ERROR;
                }
            }

            @Override
            protected void onPostExecute(Integer result) {
                if (result == HttpURLConnection.HTTP_OK) {
                    Toast.makeText(OrderDetailActivity.this, "订单取消成功", Toast.LENGTH_SHORT).show();
                    tvOrderStatus.setText("订单状态: 已取消");
                    btnCancelOrder.setVisibility(View.GONE);
                } else if (result == HttpURLConnection.HTTP_UNAUTHORIZED) {
                    Toast.makeText(OrderDetailActivity.this, "登录已过期，请重新登录", Toast.LENGTH_SHORT).show();
                    TokenUtils.clearToken(OrderDetailActivity.this);
                    finish();
                } else {
                    String msg = errorMessage.isEmpty() ? "取消订单失败" : errorMessage;
                    Toast.makeText(OrderDetailActivity.this, "取消失败：" + msg, Toast.LENGTH_LONG).show();
                }
            }
        }.execute();
    }
}
